<template>
  <div class="content">
    <div id="mapDisplay" :style="{height:offsetheight+'px'}"></div>
    <div ref="infoWindow" class="info-window-class">
      <h2 style="text-align: center">{{ infoWindowObject.name }}</h2>
          <div class="detail" v-if="infoWindowObject.grade !== 3">
            <div v-if="infoWindowObject.grade === '5.5'">
              <div v-if="parseInt(infoWindowObject.grade) < 3">
                区：{{infoWindowObject.area_name}}
              </div>
              <div v-if="parseInt(infoWindowObject.grade) < 4">
                街道：{{infoWindowObject.street_name}}
              </div>
              <div v-if="parseInt(infoWindowObject.grade) < 5">
                社区：{{infoWindowObject.community_name}}
              </div>
            </div>
            <div v-if="infoWindowObject.grade === '6'">
              <div>
                区：{{infoWindowObject.area_name}}
              </div>
              <div>
                街道：{{infoWindowObject.street_name}}
              </div>
              <div>
                社区：{{infoWindowObject.community_name}}
              </div>
              <div>
                小区：{{infoWindowObject.residential_name}}
              </div>
            </div>
<!--            <div v-if="infoWindowObject.grade === '3'">-->
<!--              <Row>-->
<!--                <Col span="8">-->
<!--                  <div>街道数</div>-->
<!--                </Col>-->
<!--                <Col span="8">-->
<!--                  <div>社区数</div>-->
<!--                </Col>-->
<!--                <Col span="8">-->
<!--                  <div>村数</div>-->
<!--                </Col>-->
<!--              </Row>-->
<!--            </div>-->
<!--            <Row>-->
<!--              <Col v-if="parseInt(infoWindowObject.grade) < 5" span="8">-->
<!--                <div>-->
<!--                  小区数-->
<!--                </div>-->
<!--              </Col>-->
<!--              <Col v-if="parseInt(infoWindowObject.grade) < 6" span="8">-->
<!--                <div>-->
<!--                  网格数-->
<!--                </div>-->
<!--              </Col>-->
<!--              <Col v-if="parseInt(infoWindowObject.grade) < 6" span="8">-->
<!--                <div>-->
<!--                  楼数-->
<!--                </div>-->
<!--              </Col>-->
<!--            </Row>-->
            <Button @click="clickLabelModel" size="small" style="position: absolute;bottom: 10px;width: 250px" v-if="parseInt(infoWindowObject.grade) === 7" type="primary">查看详情</Button>
          </div>
    </div>
    <label-info ref="labelInfo"></label-info>
  </div>
</template>

<script>

// import { getZoom } from '@/libs/util'
import { autoCenterTwo, checkLngLat, getCenter, getZoom } from '../../../../libs/util'
import {
  findBuildingLabelByMapList,
  newfindAreaList,
  newFindBuildingByMapList,
  newFindGardenByMapList,
  newFindResidentialByMapList, newGetGridInfoByID, newGetGridInfoByPolygon
} from '../../../../api/z-new-grid'
import LabelInfo from '../label-info'

export default {
  name: 'mapInfo',
  components: { LabelInfo },
  props: {
    choiceInfo: {
      type: Object
    },
    typeCheckBox: {
      type: Array
    },
    mapViewMode: {
      type: Boolean
    },
    yQmapViewMode: {
      type: Boolean
    }

  },
  data () {
    return {
      offsetheight: document.documentElement.clientHeight - 145,
      zoom: '9',
      map: null,
      areaColor: ['#D2691E', '#0000E3', '#A52A2A', '#FFE4C4', '#FFB6C1', '#556B2F', '#00FFFF', '#BC8F8F', '#4169E1', '#B0E0E6', '#FFF5EE', '#4682B4', '#9ACD32'],
      building_img: 'http://imgdl.tripln.top/webhdfs/v1/grid/label/label1656581442195_3347685345.png?op=OPEN&namenoderpcaddress=hadoop01:9000&offset=0',
      yQbuilding_img: 'http://imgdl.tripln.top/webhdfs/v1/grid/label/label1663575142189_6512020334.png?op=OPEN&namenoderpcaddress=hadoop01:9000&offset=0',
      mapPosition: null,
      infoWindowObject: {}
    }
  },
  methods: {
    init () {
      let _this = this
      setTimeout(function () {
        _this.initMap()
      }, 1000)
    },
    initMap () {
      this.map = new AMap.Map('mapDisplay', {
        resizeEnable: true,
        center: getCenter(this.choiceInfo),
        zoom: getZoom(this.choiceInfo),
        viewMode: this.mapViewMode === true ? '3D' : '2D'
      })
      if (this.mapViewMode === true) {
        this.map.setPitch(50)
        this.map.setRotation(25)
        // this.map.setpitch = 50
        // this.map.setrotation = 25
        let that = this
        let Options = {
          position: { top: '65%', right: '20%' }
        }
        that.map.plugin(['AMap.ControlBar'], function () {
          // 添加 3D 罗盘控制
          that.map.addControl(new AMap.ControlBar(Options))
        })
        that.showMapView()
      } else {
        this.showMapView()
      }
      // AMap.plugin('AMap.Geolocation', function () {
      // var geolocation = new AMap.Geolocation({
      //   enableHighAccuracy: true, // 是否使用高精度定位，默认:true
      //   timeout: 10000, // 超过10秒后停止定位，默认：5s
      //   buttonPosition: 'RB', // 定位按钮的停靠位置
      //   buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
      //   zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
      //
      // })
      // this.map.addControl(geolocation)
      // let _this = this
      // geolocation.getCurrentPosition(function (status, result) {
      //   if (status === 'complete') {
      //     _this.onComplete(result)
      //   } else {
      //     _this.onError(result)
      //   }
      // })
      // })
    },
    onComplete (data) {
      // document.getElementById('status').innerHTML = '定位成功'
      var str = []
      str.push('定位结果：' + data.position)
      str.push('定位类别：' + data.location_type)
      if (data.accuracy) {
        str.push('精度：' + data.accuracy + ' 米')
      }// 如为IP精确定位结果则没有精度信息
      str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'))
      console.log(str)
      // document.getElementById('result').innerHTML = str.join('<br>')
    },
    onError (data) {
      console.log(data.message)
    },
    showMapView () {
      this.map.clearMap()
      this.map.setZoom(getZoom(this.choiceInfo))
      switch (this.choiceInfo.grade) {
        case '2':
          this.createMaker(getCenter(this.choiceInfo))
          this.map.setCenter(getCenter(this.choiceInfo))
          this.newFindAreaList()
          break
        case '3':
          this.createMaker(getCenter(this.choiceInfo))
          this.map.setCenter(getCenter(this.choiceInfo))
          if (this.typeCheckBox.length === 1) {
            if (this.typeCheckBox[0] === 'residential') this.newFindResidentialList()
            if (this.typeCheckBox[0] === 'garden') this.newFindGardenList()
          }
          if (this.typeCheckBox.length === 2) {
            this.newFindResidentialList()
            this.newFindGardenList()
          }
          break
        case '4':
          this.createMaker(getCenter(this.choiceInfo))
          this.map.setCenter(getCenter(this.choiceInfo))
          if (this.typeCheckBox.length === 1) {
            if (this.typeCheckBox[0] === 'residential') this.newFindResidentialList()
            if (this.typeCheckBox[0] === 'garden') this.newFindGardenList()
          }
          if (this.typeCheckBox.length === 2) {
            this.newFindResidentialList()
            this.newFindGardenList()
          }
          break
        case '5':
          this.createMaker(getCenter(this.choiceInfo))
          this.map.setCenter(getCenter(this.choiceInfo))
          if (this.typeCheckBox.length === 1) {
            if (this.typeCheckBox[0] === 'residential') this.newFindResidentialList()
            if (this.typeCheckBox[0] === 'garden') this.newFindGardenList()
          }
          if (this.typeCheckBox.length === 2) {
            this.newFindResidentialList()
            this.newFindGardenList()
          }
          if (this.yQmapViewMode) {
            this.newFindBuildingListForYQ()
          } else {
            this.newFindBuildingList()
          }
          break
        case '5.5':
          this.createMaker(autoCenterTwo(this.choiceInfo.csc_mapjson, this))
          this.map.setCenter(autoCenterTwo(this.choiceInfo.csc_mapjson, this))
          if (this.typeCheckBox.length === 1) {
            if (this.typeCheckBox[0] === 'residential') this.newFindResidentialList()
            if (this.typeCheckBox[0] === 'garden') this.newFindGardenList()
          }
          if (this.typeCheckBox.length === 2) {
            this.newFindResidentialList()
            this.newFindGardenList()
          }
          if (this.yQmapViewMode) {
            this.newFindBuildingListForYQ()
          } else {
            this.newFindBuildingList()
          }
          break
        case '6':
          this.createMaker(autoCenterTwo(this.choiceInfo.csc_mapjson, this))
          this.map.setCenter(autoCenterTwo(this.choiceInfo.csc_mapjson, this))
          this.newFindGardenList()
          if (this.yQmapViewMode) {
            this.newFindBuildingListForYQ()
          } else {
            this.newFindBuildingList()
          }
          break
      }
    },
    // 展示点
    createMaker (e) {
      // var icon = new AMap.Icon({
      //   // size: new AMap.Size(20, 20), // 图标尺寸
      //   icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
      //   imageSize: new AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
      // })
      var marker = new AMap.Marker({
        position: e,
        topWhenClick: true
        // icon: icon
      })
      this.map.add(marker)
    },
    // 展示楼点
    createBuildingMaker (e1, e2, e3) {
      var icon = new AMap.Icon({
        size: new AMap.Size(20, 20), // 图标尺寸
        image: this.yQmapViewMode === true ? this.yQbuilding_img : this.building_img, // Icon的图像
        imageSize: new AMap.Size(20, 20) // 根据所设置的大小拉伸或压缩图片
      })
      var marker = new AMap.Marker({
        position: e1,
        offset: new AMap.Pixel(-20, -20),
        icon: icon,
        extData: {
          id: e3,
          grade: '7'
        }
      })
      marker.setLabel({
        offset: new AMap.Pixel(1, 0), // 设置文本标注偏移量
        content: e2, // 设置文本标注内容
        direction: 'top' // 设置文本标注方位
      })
      marker.on('click', this.markerClick)
      this.map.add(marker)
    },
    markerClick (e) {
      let data = e.target.getExtData()
      newGetGridInfoByID(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.infoWindowObject = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
      this.mapPosition = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat())
      var info = []
      info.push(this.$refs.infoWindow)
      let infoWindow = new AMap.InfoWindow({
        content: this.$refs.infoWindow
      })
      infoWindow.open(this.map, this.mapPosition)
    },
    // 地图展示多边形
    /**
     *
     * @param e1  坐标
     * @param e2  颜色
     * @param e3  类型
     * @param e4  ID
     */
    createPolygon (e1, e2, e3, e4) {
      try {
        var path = []
        if (e1) {
          let data = JSON.parse(e1)
          data.forEach(item => {
            path.push(new AMap.LngLat(item[0], item[1]))
          })
          var Polygon = {}
          if (e3 === 'area') {
            Polygon = new AMap.Polygon({
              path: path,
              strokeColor: '#1E9FFF',
              strokeWeight: 2,
              strokeStyle: 'solid',
              strokeOpacity: 1,
              fillOpacity: 0.3,
              fillColor: e2,
              zIndex: 50,
              extData: {
                type: 'area',
                id: e4
              }
            })
          }
          if (e3 === 'residential') {
            Polygon = new AMap.Polygon({
              path: path,
              strokeColor: '#FF1493',
              strokeWeight: 2,
              strokeStyle: 'solid',
              strokeOpacity: 1,
              fillOpacity: 0.3,
              fillColor: '#FF1493',
              zIndex: 40,
              extData: {
                type: 'residential',
                id: e4
              }
            })
          }
          if (e3 === 'garden') {
            Polygon = new AMap.Polygon({
              path: path,
              strokeColor: '#3CB371',
              strokeWeight: 2,
              strokeStyle: 'solid',
              strokeOpacity: 1,
              fillOpacity: 0.3,
              fillColor: '#3CB371',
              zIndex: 50,
              extData: {
                type: 'garden',
                id: e4
              }
            })
          }
          Polygon.on('click', this.PolygonClick)
          this.map.add(Polygon)
        }
      } catch (e) {
        this.$Notice.error({
          title: '获取失败',
          desc: '数据格式不正确，重新选择'
        })
      }
    },
    // 多边形点击
    PolygonClick (e) {
      let data = e.target.getExtData()
      newGetGridInfoByPolygon(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.infoWindowObject = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
      this.mapPosition = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat())
      var info = []
      info.push(this.$refs.infoWindow)
      let infoWindow = new AMap.InfoWindow({
        content: this.$refs.infoWindow
      })
      infoWindow.open(this.map, this.mapPosition)
    },
    // 查询区范围
    newFindAreaList () {
      newfindAreaList().then(ret => {
        if (ret.data.errcode === 0) {
          let data = ret.data.data
          if (data.length > 0) {
            data.forEach((item, index) => {
              if (item.company_scope) {
                if (item.code === 'LM00007') {
                  let dataRes = item.company_scope.split('-')
                  dataRes.forEach(itemRes => {
                    this.createPolygon(itemRes, this.areaColor[index], 'area', item.id)
                  })
                } else {
                  this.createPolygon(item.company_scope, this.areaColor[index], 'area', item.id)
                }
              }
            })
          }
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 查询小区
    newFindResidentialList () {
      let data = {
        grade: this.choiceInfo.grade,
        id: this.choiceInfo.id
      }
      newFindResidentialByMapList(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          result.forEach(item => {
            this.createPolygon(item.csc_mapjson, '', 'residential', item.id)
          })
        } else {
          this.$Notice.error({ title: '查询小区失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 查询网格
    newFindGardenList () {
      let data = {
        grade: this.choiceInfo.grade,
        id: this.choiceInfo.id
      }
      newFindGardenByMapList(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          result.forEach(item => {
            this.createPolygon(item.csc_mapjson, '', 'garden', item.id)
          })
        } else {
          this.$Notice.error({ title: '查询网格失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 查询楼
    newFindBuildingList () {
      let data = {
        grade: this.choiceInfo.grade,
        id: this.choiceInfo.id
      }
      newFindBuildingByMapList(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          result.forEach(item => {
            if (item.csc_mapjson) {
              let x = item.csc_mapjson.split(',')
              if (checkLngLat(x[0], x[1])) {
                this.createBuildingMaker(new AMap.LngLat(x[0], x[1]), item.name, item.id)
              }
            }
          })
        } else {
          this.$Notice.error({ title: '查询网格失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 查询楼
    newFindBuildingListForYQ () {
      this.$Message.loading({
        content: '数据查询中',
        duration: 0
      })
      let data = {
        grade: this.choiceInfo.grade,
        id: this.choiceInfo.id
      }
      findBuildingLabelByMapList(data).then(ret => {
        if (ret.data.errcode === 0) {
          let result = ret.data.data
          result.forEach(item => {
            if (item.csc_mapjson) {
              let x = item.csc_mapjson.split(',')
              if (checkLngLat(x[0], x[1])) {
                this.createBuildingMaker(new AMap.LngLat(x[0], x[1]), item.name, item.id)
              }
            }
          })
          this.$Message.destroy()
        } else {
          this.$Notice.error({ title: '查询网格失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 回调
    callBackMap (e) {
      this.$emit('callBackMap', e)
    },
    // 信息窗体
    clickLabelModel () {
      this.$refs.labelInfo.init(this.infoWindowObject)
    }
  },
  mounted () {
    this.init()
  },
  watch: {
    'infoWindowObject.id': function (newV, oldV) {
      if (newV !== oldV) {
        try {
          this.callBackMap(this.infoWindowObject)
        } catch (e) {
          // console.log('infoWindowObject.id', e)
        }
      }
    },
    'choiceInfo.id': function (newV, oldV) {
      if (newV !== oldV) {
        try {
          this.showMapView()
        } catch (e) {
          // console.log('choiceInfo.id', e)
        }
      }
    },
    'typeCheckBox.length': {
      handler (newValue, oldValue) {
        if (newValue !== oldValue && this.choiceInfo.grade !== '2') {
          try {
            this.showMapView()
          } catch (e) {
            // console.log('typeCheckBox.length', e)
          }
        }
      }
    },
    mapViewMode: function (val) {
      this.init()
    },
    yQmapViewMode: function (val) {
      this.showMapView()
    }
  },
  destroyed () {
    this.map && this.map.destroy()
  }
}
</script>

<style scoped>
#mapDisplay {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 900px;
}

#mapDisplay >>> .amap-marker-label {
  padding: 2px 6px;
  border-radius: 5px;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  text-align: center;
  font-size: 14px;
  border: 0;
  border-radius: 5px
}

.info-window-class {
  /*background-image: linear-gradient(#235CA7, #FFFFFF);*/
  background-color: #235CA7;
  width: 300px;
  height: 200px;
  color: #FFFFFF
}

.content >>> .amap-info-content {
  padding: 0px;
}
.info-window-class .detail{
  text-indent:2em;
  font-size: 12px;
}
</style>
